<?php if (!defined('BASEPATH')) exit('No direct script access allowed'); 

class Timetamer
{

/*******************************************************************************
	TimeTaMeR Class ver. 0.1
	Copyright (c) 2007, Dennis T. Kaplan
	All rights reserved.
********************************************************************************
	Redistribution and use in source and binary forms, 
	with or without modification, are permitted provided that the following conditions are met:

	    * Redistributions of source code must retain the above copyright notice, 
	    this list of conditions and the following disclaimer.
	    
	    * Redistributions in binary form must reproduce the above copyright notice, 
	    this list of conditions and the following disclaimer in the documentation and/or 
	    other materials provided with the distribution.
	    
	    * Neither the name of the finalwebsites.com nor the names of its contributors may 
	    be used to endorse or promote products derived from this software without specific 
	    prior written permission.

	THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

	_________________________________________________________________________
****************************************************************************
* To get users local time from mysql:
* $this->timetamer->ldate($row->Time);
* To get local time now:
* $this->timetamer->ldate();
****************************************************************************/

	
	function __construct()
    {
		$this->CI =& get_instance();
		log_message('debug', "TimeTaMeR Class Initialized");

        $tz = get_cookie('TZ');
        if($tz == '')
        {
            $this->time = time(); // This is GMT time see config file 
            $tz = $this->get_db_tz();
            if($tz == '')
            {
                $tz = $this->get_remote_tz();
            }
        }
        $this->tz = $tz;
	}
	
	function setTZ()
    {
		if($this->tz != putenv('TZ='.$this->tz)){
			putenv('TZ=GMT');
		}
	}

    /**
     * @note	Get timezone from database
     * @info	
     * @author	Dennis T. Kaplan
     * @access	private
     * @param	 
     * @return	string
     */	
     private function get_db_tz()
     {
         $this->CI->load->model('Tamer_Model', 'tm');
         $this->uid = $this->CI->tm->get_uid();
         if(($this->uid !== FALSE) || ($this->uid != ''))
         {
             $query = $this->CI->db->query('SELECT `timezone` FROM `contact_user` WHERE uid = '.$this->uid.' LIMIT 1');
             if ($query->num_rows() > 0) {
                 $row = $query->row();
                 if($row->timezone != '')
                 {
                     $tz = $row->timezone;
                     del_cookie('TZ');
                     set_cookie('TZ', $row->timezone, 60*60*24*365);
                 }
             }else{
                 $tz = FALSE;
             }
             return $tz;            
         }
     }
     
     private function get_remote_tz()
     {
         log_message('info', "TimeTaMeR: Getting Remote TZ");
         
         $jsta = get_cookie('JSTZ');
         if($jsta != '')
         {
             $jsta = explode(' ',$jsta);
             $tz = ltrim($jsta[6],'(');
             $tz = rtrim($tz,')');
             $tz = timezone_name_from_abbr($tz);
             if($tz == ''){
                 $tz = $this->offset_to_tz($gmt);
                 $tz= $tz[0];
             }
             if (($tz !== FALSE) && ( !is_array($tz) )){
                 set_cookie('TZ', $tz, 60*60*24*1);
             }
             return $tz;
         }
         else
         {
             $this->CI->tpl['tpljs'][]  = 'TimeTamer';
         }
     }
     

     /**
     * @note	GMT offsets to timezone
     * @info	
     * @author	Dennis T. Kaplan
     * @access	public
     * @param	$gmt either as GMT-0800 or just -0800
     * @return	string (timezone)
     */	
     public function offset_to_tz($gmt)
     {
         $tz=false;
         $offset = ltrim($gmt,'GMT');
         $timezone_identifiers = DateTimeZone::listIdentifiers();
         foreach ($timezone_identifiers as $i) {
             date_default_timezone_set($i);
             if(date('O') == $offset){
                 $tz[] = date('e');
             }
         }
         return $tz;
     }     
     
   
    /**
     * @note	Compare db tz to remote tz
     * @info	
     * @author	Dennis T. Kaplan
     * @access	private
     * @param	$db_tz,$r_tz 
     * @return	TRUE/FALSE
     */	
    private function check_db_tz($db_tz)
    {
    	putenv('TZ='.$db_tz);
        $db_time = round(time() / 60 / 60);
        if ($db_time == $this->gmt){
            putenv('TZ=GMT');
        	return TRUE;
        }
        putenv('TZ=GMT');
        return false;
    }

	function mysql_to_human($mysql = FALSE)
	{
		if($mysql !== FALSE){
			$time = strtotime($mysql);
		}
		return date('l  F dS Y \a\t h:i A',$time);
	}
    
	function ldate($time = FALSE)
	{
		// We'll remove certain characters for backward compatibility
		// since the formatting changed with MySQL 4.1
		// YYYY-MM-DD HH:MM:SS
		if($time){
			$time = str_replace('-', '', $time);
			$time = str_replace(':', '', $time);
			$time = str_replace(' ', '', $time);
			
			// YYYYMMDDHHMMSS
			$time = mktime(
				substr($time, 8, 2),
				substr($time, 10, 2),
				substr($time, 12, 2),
				substr($time, 4, 2),
				substr($time, 6, 2),
				substr($time, 0, 4)
				);
		}else{
			$time = time();
		}
		$this->setTZ();
		$time = date('r (T)', $time );
		putenv('TZ=GMT');
		return $time;
	}
}
?>
